package com.xiaochong.tir.manager.controller;


import com.xiaochong.service.common.config.oss.OSSTool;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.common.util.RedisKeysUtils;
import com.xiaochong.tir.manager.util.ReturnResult;
import com.xiaochong.tir.manager.util.SessionUtil;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.xc.logclient.utils.LogTrace;
import com.xiaochong.tir.common.data.po.Account;
import com.xiaochong.tir.common.data.po.AccountRole;
import com.xiaochong.tir.common.data.po.Role;
import com.xiaochong.tir.manager.filter.SessionManager;
import com.xiaochong.tir.manager.service.AccountRoleService;
import com.xiaochong.tir.manager.service.AccountService;
import com.xiaochong.tir.manager.service.RoleService;
import com.xiaochong.tir.manager.util.EncodeUtils;
import com.xiaochong.tir.manager.util.ManagerVersion;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 账号管理
 *
 * @author 杨松松
 **/
@Controller
@RequestMapping(ManagerVersion.API_V1_PREFIX+"/account")
@Api(value = "账号管理")
public class AccountController {

    @Autowired
    private AccountService accountService;
    @Autowired
	private RoleService roleService;
    @Autowired
    private AccountRoleService accountRoleService;
    @Autowired
    private OSSTool ossTool;
    @Autowired
    private RedisServer redisServer;
    /**
     * 账号列表页面
     *
     * @return
     */
    @RequestMapping(value = "/accountList", method = RequestMethod.GET)
    public String accountList(){
        return "/account/accountList";
    }

    /**
     * 添加账号页面
     *
     * @return
     */
    @RequestMapping(value = "/addAccountPage", method = RequestMethod.GET)
    public String addAccountPage(){
        return "/account/addAccountPage";
    }

    /**
     * 修改账号页面
     *
     * @return
     */
    @GetMapping(value = "/editAccountPage")
    @ApiImplicitParams({@ApiImplicitParam( name="id",value = "id",required = true,dataType = "Integer",paramType = "query")})
    public String editAccountPage(@RequestParam(value = "id", required = false) Integer id,
                                  Map<String, Object> map){
        Account account = new Account();
        try {
            account = accountService.getAccountById(id);
            if(null!=account){
                if(StringUtils.isNotBlank(account.getHead()) && !account.getHead().contains("http")){
                    account.setHeadKey(account.getHead());
                    account.setHead(ossTool.getOSSUrl(account.getHead()));
                }
            }
        }   catch (Exception e) {
            LogTrace.error(getClass().getSimpleName()+"/editAccountPage", e.getMessage(), e);
            map.put("msg", "编辑失败");
        }
        map.put("account", account);
        return "/account/editAccountPage";
    }

    /**
     * 添加账号
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "新增账号",notes = "新增账号")
    @RequestMapping(value = "/addAccount", method = RequestMethod.POST)
    @ResponseBody
    public Object addAccount(Account account, Map<String, Object> map) {
        redisServer.set(RedisKeysUtils.LOGINNAME,"添加账号");
        try {
            account.setPassword(EncodeUtils.md5Encode(account.getPassword()));
            Account aco = new Account();
            aco.setUserName(account.getUserName());
            Account a = accountService.selectByEntity(aco);
            if(null != a){
                return new ReturnResult<>(-1,"重复添加",1,1);
            }
            account.setCreateTime(new Date());
            accountService.insertAccount(account);
            return new ReturnResult<>(0,"添加成功",1,1);
        } catch (Exception e) {
        	LogTrace.error(getClass().getSimpleName()+"/addAccount", e.getMessage(), e);
            return new ReturnResult<>(-1,"添加失败",1,1);
        }
    }

    /**
     * 修改账号
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "修改账号",notes = "修改账号")
    @RequestMapping(value = "/modifyAccount", method = RequestMethod.POST)
    public String modifyAccount(Account account, Map<String, Object> map) {
        redisServer.set(RedisKeysUtils.LOGINNAME,"修改账号");
        try {
            if(null != account.getPassword() && !"".equals(account.getPassword())){
                account.setPassword(EncodeUtils.md5Encode(account.getPassword()));
            } else {
                account.setPassword(null);
            }
            accountService.updateAccount(account,accountService.selectByPrimaryKey(account.getId()));
            map.put("msg", "添加成功");
            return "/account/accountList";
        } catch (Exception e) {
        	LogTrace.error(getClass().getSimpleName()+"/modifyAccount", e.getMessage(), e);
            map.put("msg", "添加失败");
            return "/account/accountList";
        }

    }

    /**
     * 账号详情页面
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "查看账号",notes = "查看账号")
    @RequestMapping(value = "/accountDetail", method = RequestMethod.GET)
    public String accountDetail(HttpServletRequest request, Map<String, Object> map){
        String id = request.getParameter("id");
        try {
            if (StringUtils.isNotEmpty(id)){
                Account account = accountService.getAccountById(Integer.parseInt(id));
                if (account != null){
                    if(StringUtils.isNotBlank(account.getHead()) && !account.getHead().contains("http")){
                        account.setHead(ossTool.getOSSUrl(account.getHead()));
                    }
                    map.put("data", account);
                   //日志格式错误
                    // LogTrace.info(getClass().getSimpleName()+"/accountDetail", "accountDetail>>>id"+id+">>>data:"+account.getUserName());
                    return "/account/accountDetail";
                }
            }
        } catch (Exception e) {
        	LogTrace.error(getClass().getSimpleName()+"/accountDetail", e.getMessage(), e);
            map.put("msg", "查看详情失败");
        }
        return "/account/publish";
    }
    
	/** 
	* @Title: setAccountRole 
	* @Description: TODO(跳转账户分配角色页) 
	* @param @param id
	* @param @param model
	* @param @param map
	* @param @return
	* @param @throws DataException  
	* @return String    
	* @throws 
	*/
	@RequestMapping("/setAccountRole")
	public String setAccountRole(@RequestParam("id") Integer id, Model model, Map<String, Object> map){
		try{
			Account account = accountService.getAccountById(id);
            if(StringUtils.isNotBlank(account.getHead()) && !account.getHead().contains("http")){
                account.setHead(ossTool.getOSSUrl(account.getHead()));
            }
			List<Role> roleList = roleService.listAllRole();
			AccountRole ar = new AccountRole();
			ar.setAccountId(id);
			String roles = accountRoleService.getRolesByAccountId(ar);
			if(roles!=null){
				String[] roleArrays = roles.split(",");
				for (int i = 0; i < roleArrays.length; i++) {
					for (int j = 0; j < roleList.size(); j++) {
						if (roleArrays[i].equals(roleList.get(j).getId() + "")) {
							roleList.get(j).setIsCheck(1);
						}
					}
				}
			}
			model.addAttribute("account", account);
			model.addAttribute("roleList", roleList);
		} catch (Exception e) {
			LogTrace.error(getClass().getSimpleName()+"/setAccountRole", e.getMessage(), e);
            map.put("msg", "跳转账户分配角色页失败");
        }
		return "/account/setAccountRole";
	}

	/** 
	* @Title: saveAccountRole 
	* @Description: TODO(保存账户角色) 
	* @param @param accountId
	* @param @param roleIds
	* @param @param session
	* @param @return  
	* @return Object    
	* @throws 
	*/
    @ApiOperation(value = "分配账户角色",notes = "分配账户角色")
	@PostMapping(value = "/saveAccountRole")
	public Object saveAccountRole(@RequestParam("accountId") Integer accountId, @RequestParam("roleIds") String roleIds,
			HttpSession session, Map<String, Object> map) {
        redisServer.set(RedisKeysUtils.LOGINNAME,"分配角色");
		try{
			// 删除角色权限
			accountRoleService.deleteByAccountId(accountId);
			List<AccountRole> list = new ArrayList<AccountRole>();
			String[] arrays = roleIds.split(",");
			for (String str : arrays) {
				AccountRole accountRole = new AccountRole();
				accountRole.setAccountId(accountId);
				accountRole.setRoleId(Integer.parseInt(str));
				accountRole.setSysUserId(SessionManager.getLoginAccount(session).getId());
				list.add(accountRole);
			}
			accountRoleService.insertBatch(list);
		}catch (Exception e) {
			LogTrace.error(getClass().getSimpleName()+"/saveAccountRole", e.getMessage(), e);
            map.put("msg", "保存账户分配角色失败");
        }
		return "/account/accountList";
	}

}
